package com.example.cnotebook;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cnotebook.adapter.HomeListViewAdapter;
import com.example.cnotebook.pojo.CategoryInfo;
import com.example.cnotebook.pojo.NoteInfo;
import com.example.cnotebook.util.OKHttpUtil;
import com.example.cnotebook.util.UserConstant;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class RecycleActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, OKHttpUtil.CallBack {
    private ImageView ivBack;
    private ImageView ivDelete;
    private ListView listview;
    private TextView tvEmpty;

    private ArrayList<NoteInfo> noteInfos = new ArrayList<>();
    private ArrayList<NoteInfo> deleteNoteInfos = new ArrayList<>();
    private HomeListViewAdapter adapter;

    private SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");

    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycle);

        ivBack = findViewById(R.id.iv_back);
        ivDelete = findViewById(R.id.iv_delete);
        listview = findViewById(R.id.listview);
        tvEmpty = findViewById(R.id.tv_empty);

        ivBack.setOnClickListener(this);
        ivDelete.setOnClickListener(this);
        listview.setOnItemClickListener(this);

        adapter = new HomeListViewAdapter(this, noteInfos);
        listview.setAdapter(adapter);
        listview.setEmptyView(tvEmpty);
        getData();
    }

    private void getData() {
        OKHttpUtil.get("/note/recycle/list/" + UserConstant.userInfo.getId(), this, this);
    }


    private void initData() {
        this.noteInfos.clear();
        ArrayList<CategoryInfo> categoryInfos = UserConstant.categoryInfos;
        Date date = null;
        for (int i = 0; i < deleteNoteInfos.size(); i++) {
            NoteInfo noteInfo = deleteNoteInfos.get(i);
            noteInfo.setCreateDateTime(noteInfo.getCreateDate());
            if (noteInfo.getCategoryId() == -1) noteInfo.setCategoryName("未分类");
            if (i == 0) {
                date = noteInfo.getCreateDate();
            } else {
                if (format.format(noteInfo.getCreateDate()).equals(format.format(date))) {
                    noteInfo.setCreateDate(null);
                } else {
                    date = noteInfo.getCreateDate();
                }
            }
            for (CategoryInfo categoryInfo : categoryInfos) {
                if (categoryInfo.getId().equals(noteInfo.getCategoryId())) {
                    noteInfo.setCategoryName(categoryInfo.getName());
                }
            }
            this.noteInfos.add(noteInfo);
        }
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("选择操作")
                .setMessage("您想恢复还是永久删除该条笔记？")
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        OKHttpUtil.get("/note/delete/" + noteInfos.get(position).getId(), new OKHttpUtil.CallBack() {
                            @Override
                            public void onSuccess(JSONObject response) throws JSONException {
                                if (response.getInt("code") == 1000) {
                                    Toast.makeText(RecycleActivity.this, "删除成功!", Toast.LENGTH_SHORT).show();
                                    noteInfos.remove(position);
                                    adapter.notifyDataSetChanged();
                                }
                            }

                            @Override
                            public void onFailure(int errorNo, String strMsg) {

                            }
                        }, RecycleActivity.this);
                    }
                })
                .setNegativeButton("恢复", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("id", noteInfos.get(position).getId());
                            jsonObject.put("isDelete", 1);
                            OKHttpUtil.post("/note/update", jsonObject, new OKHttpUtil.CallBack() {
                                @Override
                                public void onSuccess(JSONObject response) throws JSONException {
                                    if (response.getInt("code") == 1000) {
                                        Toast.makeText(RecycleActivity.this, "已恢复!", Toast.LENGTH_SHORT).show();
                                        noteInfos.remove(position);
                                        adapter.notifyDataSetChanged();
                                        UserConstant.homeIsSaveData = true;
                                        UserConstant.userIsSaveData = true;
                                    }
                                }

                                @Override
                                public void onFailure(int errorNo, String strMsg) {

                                }
                            }, RecycleActivity.this);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }).create();
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_delete:
                deleteAllNote();
                break;
        }
    }

    private void deleteAllNote() {
        OKHttpUtil.get("/note/deleteAll/" + UserConstant.userInfo.getId(), new OKHttpUtil.CallBack() {
            @Override
            public void onSuccess(JSONObject response) throws JSONException {
                if (response.getInt("code") == 1000) {
                    Toast.makeText(RecycleActivity.this, "删除成功!", Toast.LENGTH_SHORT).show();
                    noteInfos.clear();
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {

            }
        }, this);
    }

    @Override
    public void onSuccess(JSONObject response) throws JSONException {
        this.deleteNoteInfos.clear();
        JSONArray data = response.getJSONArray("data");
        for (int i = 0; i < data.length(); i++) {
            deleteNoteInfos.add(gson.fromJson(data.getJSONObject(i).toString(), NoteInfo.class));
        }
        initData();
    }

    @Override
    public void onFailure(int errorNo, String strMsg) {

    }
}
